import Fuse from "fuse.js";

/**
 * 从数组中随机选择指定数量的元素
 * @param {Array<T>} arr - 源数组
 * @param {number} count - 需要随机选择的元素数量
 * @returns {Array<T>} - 随机选择的元素组成的新数组
 */
export const getRandomElements = <T>(arr: T[], count: number): T[] => {
  // 处理边界情况
  if (!Array.isArray(arr) || arr.length === 0 || count <= 0) {
    return [];
  }

  // 如果源数组长度小于等于需要选择的数量，直接返回源数组的副本
  if (arr.length <= count) {
    return [...arr];
  }

  // 使用Fisher-Yates洗牌算法随机排序数组的前count个元素
  const shuffled = [...arr];
  for (let i = 0; i < count; i++) {
    const randomIndex = i + Math.floor(Math.random() * (shuffled.length - i));
    // 交换当前元素与随机选择的元素
    [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]];
  }

  // 返回前count个元素
  return shuffled.slice(0, count);
};

/**
 * 传入uri，返回一个新的url
 * @param targetUri
 */
export const getTargetUrl = (targetUri: string) => {
  // 解析当前页面的URL和查询参数
  const currentUrl = new URL(useRequestURL().href);
  const currentParams = new URLSearchParams(currentUrl.search);
  currentParams.delete("gameId");
  currentParams.delete("searchValue");
  currentParams.delete("categoryType");

  // 解析目标URL
  const targetUrlObj = new URL(targetUri, useRequestURL().origin);
  const targetParams = new URLSearchParams(targetUrlObj.search);

  // 将当前页面的参数合并到目标参数中，如果目标已有该参数则跳过
  currentParams.forEach((value, key) => {
    if (!targetParams.has(key)) {
      targetParams.set(key, value);
    }
  });

  targetUrlObj.search = targetParams.toString();
  return targetUrlObj.pathname + targetUrlObj.search;
};

/** 获取公共上报数据 */
export const getTrackCommonParams = () => {
  const { channel = "", network = "" } = useRoute().query;
  const Page =
    pageInfor.find((item) => item.pathname === useRequestURL().pathname)?.trackPage || "";
  const commonParams = {
    Network: network,
    Channel: channel,
    Page,
  };
  return commonParams;
};

/**
 * 获取渲染的图片路径
 * @param isAutoImg 是否为动态拼接图片，也就是无http打头的
 * @param src 图片链接
 * @returns
 */
export const getSrc = (srcValues: GetSrcType) => {
  const { src = "", isAutoImg = false } = srcValues;
  const isDev = process.env.NODE_ENV === "development";
  if (isAutoImg) {
    return isDev ? `/_nuxt/public/img/${src}` : `/img/${src}`;
  } else {
    return src;
  }
};

/**
 * 生成图片链接
 * @param imgSrcValue 一些参数
 * @returns
 */
export const getImgSrc = (imgSrcValue: ImgSrcType) => {
  const { v4Pre, siteName, imgNext } = imgSrcValue;
  return `https://${v4Pre}.${siteName}.com/icons/${imgNext}.png`;
};

/**
 * 获取域名，服务端的
 * @returns 域名
 */
export const getHostName = () => {
  const hostName = useRequestURL().hostname;
  const newHostName = hostName.includes(".com") ? hostName : "localhost";
  return useRuntimeConfig()?.public?.host || newHostName;
};

/**
 * 模糊匹配数组数据
 * @param fuseSearch
 * @returns
 */
export const fuseSearchFun = (fuseSearch: FuseSearchType) => {
  const { list = [], keys = [], value = "" } = fuseSearch;
  const fuse = new Fuse(list, {
    keys,
    shouldSort: true,
  });
  const result = fuse.search(value);
  return result.map((item: any) => item.item);
};

/**
 * 随机选择一个游戏id
 * @returns 游戏数据
 */
export const getRandomGameDatail = async (): Promise<GameJson> => {
  const { data } = await useFetch<GameJson>("/api/getRandomGameApi", {
    method: "POST",
    body: {
      hostName: getHostName(),
    },
  });
  return data.value as GameJson;
};

/**
 * DIY输出log日志
 * @param value 被输出的日志
 */
export const diyConsole = (value: string = "") => {
  console.log(
    "%c%s",
    "background:#233f33;padding:2px 8px;border-radius:2px;color:#ffffff90",
    value,
  );
};

/**
 * 在运行时分析CPU和内存使用，避免内存溢出和CPU占用过高
 * @description 开发环境下运行，生产环境下不使用
 */
export const initCpu = async () => {
  const { isShowCPU } = useRuntimeConfig().public;
  if (Number(isShowCPU) == 0) return;
  const data = await $fetch<NodeCpuType>("/api/getCPU", {
    method: "POST",
    body: {
      hostName: getHostName(),
    },
  });
  const { cpu, memory } = data || {};
  diyConsole(cpu);
  diyConsole(memory);
};
